package com.tlgen.controller.technology;

import com.tlgen.model.Department;
import com.tlgen.model.Enlist;
import com.tlgen.model.RespBean;
import com.tlgen.model.RespPageBean;
import com.tlgen.service.DepartmentService;
import com.tlgen.service.EnlistService;
import com.tlgen.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author: tlgen
 * @Discription:
 */
@RestController
@RequestMapping("/technology/enlist")
public class EnlistConcroller {

    @Autowired
    EnlistService enlistService;

    @Autowired
    DepartmentService departmentService;

    @GetMapping("/")
    public RespPageBean getEnlistByPage(@RequestParam(defaultValue = "1") Integer page,
                                          @RequestParam(defaultValue = "10") Integer size,
                                          Enlist enlist) {
        return enlistService.getEnlistByPage(page, size, enlist);
    }

    @PostMapping("/")
    public RespBean addEnlist(@RequestBody Enlist enlist) {
        if (enlistService.addEnlist(enlist) == 1) {
            return RespBean.ok("添加成功!");
        }
        return RespBean.error("添加失败!!");
    }

    @GetMapping("/deps")
    public List<Department> getAllDepartments() {
        return departmentService.getAllDepartments();
    }

    @DeleteMapping("/{id}")
    public RespBean deleteEnlistByEid(@PathVariable Integer id) {
        if (enlistService.deleteEnlistByEid(id) == 1) {
            return RespBean.ok("删除成功!");
        }
        return RespBean.error("删除失败!");
    }

    @PutMapping("/")
    public RespBean updateEnlist(@RequestBody Enlist Enlist) {
        if (enlistService.updateEnlist(Enlist) == 1) {
            return RespBean.ok("更新成功!");
        }
        return RespBean.error("更新失败!");
    }

    //poi接口 导出
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportData() {
        //先得到要导出的数据嘛 这哩的page size可以为空是 在sql语句中<c:if 才能生效
        List<Enlist> list = (List<Enlist>) enlistService.getEnlistByPage(null, null,
                null).getData();
        return POIUtils.enlist2Excel(list);
    }

    //导入 getAllDepartmentsWithOutChildren 是获取部门的时候不要哩边的children
    @PostMapping("/import")
    public RespBean importData(MultipartFile file) {
        List<Enlist> list = POIUtils.excel2enlist(file, departmentService.getAllDepartmentsWithOutChildren());
        //数据插入到数据库中
        if (enlistService.addEnlists(list) == list.size()) {
            return RespBean.ok("导入成功!");
        }
        return RespBean.error("导入失败!");
    }
}
